package com.liser.material.design.ui.login;

import android.content.Intent;
import android.util.Log;
import android.widget.EditText;

import com.google.gson.Gson;
import com.liser.material.design.MainActivity;
import com.liser.material.design.R;
import com.liser.material.design.framework.helper.SharedPreferencesHelper;
import com.liser.material.design.framework.ui.BaseActivity;
import com.liser.material.design.net.Network;
import com.liser.material.design.net.NetworkSubs;
import com.liser.material.design.net.model.LoginRequest;
import com.liser.material.design.net.model.LoginResponse;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.liser.material.design.framework.helper.SharedPreferencesHelper.USER_OBJECT;

public class LoginActivity extends BaseActivity {

    private static final String TAG = LoginActivity.class.getName();

    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;

    @BindView(R.id.username)
    EditText loginEdtUname;

    @BindView(R.id.password)
    EditText loginEdtPwd;

    @Override
    protected int onLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void onView() {
        initTopBar();
    }

    private void initTopBar() {
        mTopBar.addLeftBackImageButton().setOnClickListener(view -> {
            finish();
            overridePendingTransition(R.anim.slide_still, R.anim.slide_out_right);
        });
        mTopBar.setTitle("登录");
    }

    /**
     * 登录
     */
    @OnClick(R.id.login)
    public void onLoginClick() {
        String username = loginEdtUname.getText().toString();
        String password = loginEdtPwd.getText().toString();
        Log.i(TAG, "用户名：" + username + " 密码：" + password);
        netWork(username, password);
    }

    private void netWork(String username, String password) {
        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setUsername(username);
        loginRequest.setPassword(password);
        Network.api()
                .login(loginRequest)
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NetworkSubs<LoginResponse>() {
                    @Override
                    protected void onSuccess(LoginResponse data) {
                        String jsonString = new Gson().toJson(data);
                        SharedPreferencesHelper.put(USER_OBJECT, jsonString);
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                    }
                });
    }
}